import { Router, Request, Response, text, json } from "express";
const config = require("config-lite")(__dirname);
import encrypt from "../libs/tools/encrypt"
import Mysql_Moudle from "../libs/sqlcmd/mysql";
let MYSQL = new Mysql_Moudle(config.mysql);
import { Req } from "../libs/tools/Tools"
import rds from "../libs/redis/redis"
import WX from "../libs/tools/wechat";
import { info } from "console";
const jwt = require('jsonwebtoken');
const path = require("path")
let cli = new rds(config.redis.host, config.redis.port, config.redis.password);
let key = "dhand123"
const data_ret = require('../libs/ret_data.json');
// 生成Token (有效期不限)
function generateToken(userId, phone, type) {
    return jwt.sign(
        {
            id: userId,
            phone: phone,
            type: type
        },
        config.jwt.secret,
        // { expiresIn: '24h' }
    );
}

/** ---------  常用类库!结束!-------------- */
const router = Router();

router.post("/get_phone", async (req, res) => {
    let answer: any = {};
    let code = req.body.code;
    let encryptedData = req.body.encryptedData;
    let iv = req.body.iv;
    let wx_code = req.body.wx_code;

    answer = await Req.get("https://api.weixin.qq.com/sns/jscode2session", {
        appid: config.mpWeixin.AppID,
        secret: config.mpWeixin.AppSecret,
        js_code: wx_code,
        rant_type: "authorization_code"
    });
    let answerO = JSON.parse(answer.toString());
    let sql = `INSERT INTO wx_code2session_log_fil (ins_date,ip,code,message,type)VALUES(NOW(),'${req.ip}',${answerO.errcode ? answerO.errcode : 0},'${answer}','')`;
    let result = await MYSQL.Query(sql);
    await cli.hset("kg_wx_yz", answerO.openid, answerO.session_key);

    let phone = await get_phone(encryptedData, iv, answerO.openid)
    if (!phone) {
        data_ret.code = 400
        data_ret.msg = "获取手机号失败"
        data_ret.icon = "error"
        return res.json(data_ret);
    }

    // 查询手机号  没有新增  有的话 更新 optionid
    let sql_phone = `SELECT * FROM lb_users WHERE phone='${phone}'`;

    let phone_ret = await MYSQL.Query(sql_phone);
    let token = ""
    let info = {}
    if (phone_ret.length == 0) {
        let sql_insert = await MYSQL.Insert({ phone: phone, openid: answerO.openid, status: 2, ins_date: new Date() }, "wg_users")
        let installl = await MYSQL.Query(sql_insert)
        token = generateToken(installl.insertId, phone, "wxChar")
        await cli.hset("wg_users", installl.insertId, token);

    } else {
        let sql_update = await MYSQL.Update({ openid: answerO.openid }, "wg_users", { id: phone_ret[0].id })
        token = generateToken(phone_ret[0].id, phone_ret[0].phone, "wxChar")
        await cli.hset("wg_users", phone_ret[0].id, token);

    }
    info = await MYSQL.Query(sql_phone);
    data_ret.data = { token: token, info: info };
    return res.json(data_ret);
});

async function get_phone(encryptedData_ret, iv_ret, openid_ret) {
    let session_key = await cli.hget("kg_wx_yz", openid_ret);
    if (!session_key) {
        return false;
    }
    //这个不应该是上传的
    let encryptedData = encryptedData_ret;
    let iv = iv_ret;
    let obj = encrypt.WX_desDecrypt(session_key, encryptedData, iv);
    //得到手机号
    let phone = obj.phoneNumber;

    return phone;
}


export default router;